package com.dl.base.ui

import android.os.Bundle
import android.os.Looper
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.dl.base.ui.dialog.AppProgressDialog
import com.dl.base.ui.utils.hideSoftKeyboard
import com.dl.base.ui.utils.isClickEditText
import com.dl.base.ui.utils.themeStatusBar

abstract class BaseActivity<T : ViewDataBinding> : AppCompatActivity() {
    val viewBinding: T by lazy { DataBindingUtil.setContentView<T>(this, setContentView()) }
    private var loadingDialog: AppProgressDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding.lifecycleOwner = this
        init(savedInstanceState)
        Looper.myQueue().addIdleHandler {
            lazyInit(savedInstanceState)
            false
        }
        window.themeStatusBar()
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_DOWN) {
            //当前点击的view不是editText时关闭软键盘
            val view = currentFocus
            view?.let {
                if (it.isClickEditText(ev)) {
                    it.hideSoftKeyboard()
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        return if (window.superDispatchTouchEvent(ev)) {
            true
        } else onTouchEvent(ev)
    }

    abstract fun setContentView(): Int
    abstract fun init(bundle: Bundle?)

    open fun enableRouterInject(): Boolean = false
    open fun enableEventBus(): Boolean = false

    /**
     * 主线程空闲使运行执行的初始化操作
     */
    open fun lazyInit(bundle: Bundle?) {}


    open fun showDialog(msg: String? = null) {
        if (loadingDialog?.isShowing == true) {
            return
        }

        loadingDialog = AppProgressDialog(this)
        loadingDialog?.show(msg)
    }

    open fun dismissDialog() {
        loadingDialog?.dismiss()
        loadingDialog = null
    }
}